<template>
  <div class="chart" ref="chart02Ref">图表的容器</div>
</template>

<script setup>
import { computed, inject, onMounted, ref, watchEffect } from 'vue'
import { countWages } from '../../../api/salary'

const chart02Ref = ref(null)
const $echarts = inject('echarts')
const searchData = inject('searchData')

const wagesCount = ref([])

const achive = async () => {
  // 注释
  // const data = ref(['各部门最大工资', '各部门平均工资'])

  //获取数据
  const res = await countWages(searchData.date)
  Object.assign(wagesCount.value, res.data.wagesCount) //整体赋值

  // 部门数组
  const department = computed(() => {
    return wagesCount.value.map((item) => item.department)
  })
  // 创建数据数组
  const result = computed(() => {
    return [
      {
        data: wagesCount.value.map((item) => item.sumWages / 1000),
        type: 'bar',
        name: '总工资'
      },
      {
        data: wagesCount.value.map((item) => item.avgWages / 1000),
        type: 'line',
        name: '平均工资',
        yAxisIndex: 1 // 使用第二个y轴（平均工资）
      }
    ]
  })

  if (chart02Ref.value) {
    const myChart = $echarts.init(chart02Ref.value)
    myChart.setOption({
      title: {
        text: '各部门总工资及平均工资'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['总工资', '平均工资'],
        left: 'right'
      },
      xAxis: {
        type: 'category',
        data: department.value
      },
      yAxis: [
        {
          type: 'value',
          name: '总工资 /千元',
          axisLabel: {
            formatter: '{value} '
          }
        },
        {
          type: 'value',
          name: '平均工资 /千元',
          position: 'right',
          axisLabel: {
            formatter: '{value} '
          }
        }
      ],
      series: result.value
    })
  }
}
watchEffect(async () => {
  // console.log(searchData.date, 'searchData updated')

  if (searchData.date) {
    await achive()
  }
})
onMounted(async () => {
  await achive()
})
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
